package com.uwlaser.socket.exception;

import lombok.Data;

/**
 * @Author QZK
 * @Description TODO Socket【异常类】
 * @Date 2022-12-05-16:19
 * @Version 1.0
 */
@Data
public class TcpSocketException extends Exception {

    /**
     * 异常类型
     */
    private static final String type = "Socket";
    /**
     * 地址
     */
    private String host;
    /**
     * 端口
     */
    private Integer port;

    /**
     * 参数
     */
    private String params;

    /**
     * 连接方式：长连接或者短连接
     */
    private String mode;

    /**
     * 描述
     */
    private String describe;

    /**
     * 请求结果
     */
    private String requestResult;

    public TcpSocketException(String host, Integer port, String params,String mode, String describe ,String message,String requestResult) {
        super(handleMsgLength(message));
        this.host = host;
        this.port = port;
        this.params = params;
        this.mode = mode;
        this.describe = describe;
        this.requestResult = requestResult;
    }

    public TcpSocketException(String host, Integer port, String params,String mode, String describe ,String message) {
        super(handleMsgLength(message));
        this.host = host;
        this.port = port;
        this.params = params;
        this.mode = mode;
        this.describe = describe;
    }

    public TcpSocketException(String message, String describe) {
        super(handleMsgLength(message));
        this.describe = describe;
    }

    public TcpSocketException(String message) {
        super(handleMsgLength(message));
    }

    /**
     * 处理异常
     * @return
     */
    public static TcpSocketException handleException(String host, Integer port, String params, String mode, Exception e){
        TcpSocketException te = null;
        if(e instanceof TcpSocketException){
            //统一设置异常数据
            te = (TcpSocketException) e;
            te.setHost(host); //地址
            te.setPort(port); //端口
            te.setParams(params); //参数
            te.setMode(mode); // 调用模式
        } else {
            //其他异常默认按照代码异常和数据异常处理
            te = new TcpSocketCodeErrorException(host,port,params,mode,"调用Socket接口发生异常："+e.getMessage());
        }
        return te;
    }

    /**
     * 处理消息长度
     * @return
     */
    private static String handleMsgLength(String message){
        if(message != null && message.length() > 500){
            message = message.substring(0,500);
        }
        return "【请求外部系统异常】" +  message;
    }
}
